<template>
  <div class="app-container">
    <div class="content">
      <el-row style="padding-bottom: 10px;">
        <el-col>
          <el-button type="success" size="small"    class="el-icon-download" @click="exportTemplateFile" style="margin-bottom: 5px;">导出德育模板</el-button>
            <el-upload
                style="width:100px;display: contents;"
                ref="upload"
                name="upload"
                class="upload-demo"
                :action="upload.url"
                :headers="upload.headers"
                :before-upload="handlePreview"
                :on-remove="handleRemove"
                :on-success="handleFileSuccess"
                :show-file-list="false"
                multiple
                :limit="1"
                :on-exceed="handleExceed"
                :file-list="fileList">
                <el-button type="primary" size="small"  class="el-icon-upload2" :loading="importLoading">上传德育评价</el-button>
              </el-upload>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="20">
          <div class="leftBox">
            <el-card style="padding-bottom: 10px">
              <div class="title">
                {{ stuEvaPlan.planName }}
              </div>
              <div style="padding: 0px 0px 15px 0px; text-align: center">
                <!-- <span>当前学生：{{ termTime.remarks }} </span> -->
                <!-- <el-row :gutter="8"> -->
                <!-- <el-col :span="8">
                    <span>姓名：{{ student.name }}</span>
                  </el-col>
                  <el-col :span="8">
                    <span>班级：{{ classInfo.className }} </span>
                  </el-col> -->
                <!-- <el-col :span="8"> -->
                <span>考评学期：{{ termTime.remarks }} </span>
                <!-- </el-col> -->
                <!-- </el-row> -->
              </div>
              <div style="padding: 0px 0px 15px 0px;">
                <span>学生姓名：{{ student.name }} </span>
              </div>
              <div class="evaTable">
                <el-table
                  :data="tableData"
                  :span-method="objectSpanMethod"
                  :summary-method="getSummaries"
                  show-summary
                  border
                  style="width: 100%"
                >
                  <el-table-column
                    prop="indicator"
                    label="考评指标"
                    width="100px"
                  >
                  </el-table-column>
                  <el-table-column
                    prop="element"
                    label="二级考评指标"
                    width="120px"
                  ></el-table-column>
                  <el-table-column prop="remark" label="备注">
                    <template slot-scope="scope">
                      <span v-if="scope.row.isNewAdd==1">
                        <el-input v-model="scope.row.remark" type="textarea" :rows="5">
                        </el-input>
                      </span>
                      <span v-else>{{ scope.row.remark }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="grade" label="得分" width="120px">
                    <template slot-scope="scope">
                      <!-- <span v-if="scope.row.isNewAdd==1"> -->
                        <el-input v-model="scope.row.grade" type='number' @blur="checkRight(scope.row.grade)">
                        </el-input>
                      <!-- </span> -->
                      <!-- <span v-else>{{ scope.row.remark }}</span> -->
                    </template>                  
                    <!-- <template slot-scope="scope">
                      <el-select v-if="scope.row.isNewAdd!=1"
                        v-model="scope.row.grade"
                        clearable
                        filterable
                        style="width: 100%"
                      >
                        <el-option
                          v-for="item in gradeOption"
                          :key="item.dictValue"
                          :label="item.dictLabel"
                          :value="item.dictValue"
                        >
                        </el-option
                      ></el-select>
                    </template> -->
                  </el-table-column>
                </el-table>
                <div style="padding: 15px 0 0 0; float: right">
                  <el-button @click="save()" icon="el-icon-check" :loading="importLoading">保存评价</el-button>
                  <el-button @click="submitData()" icon="el-icon-finished" type="primary" :loading="importLoading">提交评价</el-button>
                </div>
              </div>
            </el-card>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="rightBox">
            <el-card class="box-card">
              <div class="title">
                <span>班级：{{ classInfo.className }}</span>
              </div>
              <el-radio-group v-model="student.id">
                <el-radio
                  v-for="item in studentList"
                  :key="item.id"
                  :label="item.id"
                  class="text item"
                  style="padding: 0px 0px 15px 0px; width: 100%"
                  @change="echoData(item.id)"
                  >{{ item.name }} <i class="el-icon-check" style="color:#67c23a;font-weight: bold;" v-if="isSaveScore(item.id)"></i></el-radio
                >   
              </el-radio-group>
            </el-card>
            <div slot="tip" class="el-upload__tip" style="color:red;padding:10px 0 0 0">
              <span style="font-size:20px">tips:</span>
              <span style="font-size:12px">请填写完成后先保存，再提交</span>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import { findStuEvaPlanById ,createStuEvaDataBatch,findStuEvaDataByTaskId,exportTemplate} from "@/api/stu/evaluation/plan";
import {
  findStuEvaScoreTemplateByPlanId,
  findStudentByClassId,
  findClassInfoByClassId,
} from "@/api/stu/evaluation/task";
import { getTermtime } from "@/api/system/termtime";
import { getDicts } from "@/api/system/dict/data";
import { getToken } from '@/utils/auth'


export default {
  name: "score",
  data() {
    return {
      importLoading:false,
      upload:{
          // 设置上传的请求头部
          headers: { Authorization: "Bearer " + getToken() },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/stu/evaluation/data/import",
        },
      //考评任务
      stuEvaTask: {
        id: undefined,
        // taskName: undefined,
        stuEvaPlanId: undefined,
        classId: undefined,
        termTimeId: undefined,
        evaStatus:undefined,
        importLoading:false,
        
      },
      //表格数据
      tableData: [],
      //评分option
      gradeOption: ["A", "B", "C"],
      //当前班级所有学生
      studentList: [],
      //当前学生
      student: {
        id: undefined,
        name: undefined,
      },
      //完成考评学生名单
      finishStu: [],
      //当前班级信息
      classInfo: {
        id: undefined,
        className: undefined,
      },
      //当前考评方案名称
      stuEvaPlan: {
        id: undefined,
        planName: undefined,
      },
      //学年学期
      termTime: {
        id: undefined,
        remarks: undefined,
      },
      //计数器
      counter: undefined,
      //提交的数据
      stuEvaData: [],
      mergeSpanArr:[],
      mergeSpanArrIndex:null,
      fileList:[]
    };
  },
  mounted() {
    window.addEventListener("beforeunload", (e) => {
      this.beforeunloadHandler(e);
    });
  },
  destroyed() {
    window.removeEventListener("beforeunload", (e) => {
      this.beforeunloadHandler(e);
    });
  },
  created() {
    // this.stopF5Refresh();
    //获取上个页面的数据
    this.stuEvaTask = this.$route.query;
    if(this.stuEvaTask.id){
      this.getTaskDetails(this.stuEvaTask.id)
    }
    const _this = this
    //初始化表格数据
    this.initTableData();
    // findStuEvaScoreTemplateByPlanId(this.stuEvaTask.stuEvaPlanId).then(
    //   (resp) => {
    //     this.tableData = resp.data;
    //     this.tableData.push({indicator:"综合评价",grade:"",remark:"",element:"",isNewAdd:"1"})
    //     _this.setMergeArr(resp.data)
    //   }
    // );
    //初始化当前班级所有学生数据
    findStudentByClassId(this.stuEvaTask.classId).then((resp) => {
      this.studentList = resp.data;
      // this.counter = 0;
      // this.student = this.studentList[this.counter];
    });
    //根据当前班级id获取班级信息
    findClassInfoByClassId(this.stuEvaTask.classId).then((resp) => {
      this.classInfo = resp.data;
    });
    //获取考评方案信息
    findStuEvaPlanById(this.stuEvaTask.stuEvaPlanId).then((resp) => {
      this.stuEvaPlan = resp.data;
    });
    //获取学期信息
    getTermtime(this.stuEvaTask.termTimeId).then((resp) => {
      this.termTime = resp.data;
    });
    getDicts("stu_eva_grade").then(resp => {
      this.gradeOption = resp.data
    })
  },
  methods: {
    handleRemove(file, fileList) {
      // console.log(file, fileList);
    },
    handlePreview(file) {
      // console.log(file);
      // if(this.stuEvaData.length>0){
      //   this.$message.warning(`修改过的评估不能导入,请人工修改；如果想重新上传请刷新当前页面`);
      //   return false
      // }
      this.importLoading = true

    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    // 更新导入文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.stuEvaData = response.data
      this.importLoading = false
      this.msgSuccess("成绩上传成功");
      this.fileList = [];
      // console.log(this.form)
    },
    exportTemplateFile(){
      let obj = this.examItem
      exportTemplate(this.stuEvaTask.stuEvaPlanId,this.stuEvaTask.classId,this.stuEvaTask.id,this.termTime.remarks,this.stuEvaPlan.planName).then(response=>{
        this.fileDownload(response.data, "考试成绩录入模板.xlsx");
      })
    },
    initTableData(){
      if(this.stuEvaTask.evaStatus == 0){
        findStuEvaScoreTemplateByPlanId(this.stuEvaTask.stuEvaPlanId).then(
          (resp) => {
            this.tableData = resp.data;
            // this.tableData.push({indicator:"综合评价",grade:"",remark:"",element:"",isNewAdd:"1"})
            this.setMergeArr(resp.data)
            
          }
        );        
      }else{
        findStuEvaDataByTaskId(this.stuEvaTask.id).then(resp =>{
          if(resp.data.length > 0){
            let obj = JSON.parse(resp.data[0].result);
            obj.forEach(item=>{
              item.grade = "";
              if(item.isNewAdd){
                item.remark = "";
                // this.tableData.push({indicator:"综合评价",grade:"",remark:"",element:"",isNewAdd:"1"})
              }
            }) 
            this.setMergeArr(obj)
            this.tableData = obj;           
          }
        })
      }
    },

    getTaskDetails(id){
      findStuEvaDataByTaskId(id).then(resp=>{
        this.stuEvaData = resp.data
      })
    },
    submitData(){
      console.log(this.tableData)
      if(this.stuEvaData.length != this.studentList.length ){
        this.$confirm('有学生的评价未保存，确认提交吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          createStuEvaDataBatch(this.stuEvaData).then(resp=>{
            this.$message({ message: "提交成功", type: "success" });
            this.$router.push({path:"/stuEvaluation/task"});
          })
        }).catch(()=>{

        })
      }else{
        createStuEvaDataBatch(this.stuEvaData).then(resp=>{
          this.$message({ message: "提交成功", type: "success" });
          this.$router.push({path:"/stuEvaluation/task"});
        })
      }
      
    },
    isSaveScore(studentId){
      let flag = false
      this.stuEvaData.forEach(item=>{
        if(item.studentId==studentId){
          flag = true
        }
      })
      return flag
    },
    //提交
    save() {
      if(!this.student.id){
        this.$message({ message: "请选择学生", type: "warning" });
        return
      }

      //获取学生姓名
      for (var i = 0; i < this.studentList.length; i++) {
        if (this.student.id === this.studentList[i].id) {
          this.student.name = this.studentList[i].name;
        }
      }

      let obj = {
        studentId: this.student.id,
        studentName: this.student.name,
        classId: this.classInfo.id,
        className: this.classInfo.className,
        evaPlanName: this.stuEvaPlan.planName,
        termTimeName: this.termTime.remarks,
        result: JSON.stringify(this.tableData),
        taskId: this.stuEvaTask.id
      };
      let num = 0

      this.stuEvaData.forEach((item,index)=>{
        if(item.studentId==obj.studentId){
          item = obj
          this.stuEvaData.splice(index,1,obj)
        }else{
          num++
        }
        
      })
      if(num==this.stuEvaData.length){
        this.stuEvaData.push(obj);
      }
      
      this.$message({ message: "保存成功", type: "success" });
     
    },

    echoData(value) {
      //每次选择学生后清空tableData的grade数据
      for (var i = 0; i < this.tableData.length; i++) {
        this.tableData[i].grade = "";
      }

      if(this.tableData[this.tableData.length - 1].indicator === "综合评价"){
        this.tableData[this.tableData.length - 1].remark = '';
      }

      for (var i = 0; i < this.studentList.length; i++) {
        if (value === this.studentList[i].id) {
          this.student.name = this.studentList[i].name;
        }
      }
      for (var i = 0; i < this.stuEvaData.length; i++) {
        if (this.stuEvaData[i].studentId === value) {
          console.log(this.stuEvaData[i])
          let jsonStr = JSON.parse(this.stuEvaData[i].result);
          console.log(jsonStr)
          this.tableData = jsonStr
          console.log(this.tableData)
        }
      }
      
      
    },
    stopF5Refresh() {
      document.onkeydown = function (e) {
        var evt = window.event || e;
        var code = evt.keyCode || evt.which;
        //屏蔽F1---F12
        if (code > 111 && code < 124) {
          if (evt.preventDefault) {
            evt.preventDefault();
          } else {
            evt.keyCode = 0;
            evt.returnValue = false;
          }
        }
      };
      //禁止鼠标右键菜单
      document.oncontextmenu = function () {
        return false;
      };
      //阻止后退的所有动作，包括 键盘、鼠标手势等产生的后退动作。
      history.pushState(null, null, window.location.href);
      window.addEventListener("popstate", function () {
        history.pushState(null, null, window.location.href);
      });
    },

    beforeunloadHandler(e) {
      e = e || window.event;
      if (e) {
        e.returnValue = "您是否确认离开此页面-您输入的数据可能不会被保存";
      }
      return "您是否确认离开此页面-您输入的数据可能不会被保存";
    },

    //计算总分
      getSummaries(param) {
        const { columns, data } = param;
        const sums = [];

        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '总分';
            return;
          }
          if (index === 2) {
            sums[index] = '-';
            return;
          }
          const values = data.map(item => Number(item[column.property]));
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value) || value != '') {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
            sums[index] += '';
          } else {
            sums[index] = '-';
          }
        });
        return sums;
      },

    //合并单元格
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      
      if (columnIndex === 0) {//这个是你要合并的规则
          const _row = this.mergeSpanArr[rowIndex];
          const _col = _row > 0 ? 1 : 0;
          return {
            rowspan: _row,
            colspan: 1
          };
        }
      },
      setMergeArr(data) {
      this.mergeSpanArr=[]
      for (var i = 0; i < data.length; i++) {
        if (i === 0) {
          this.mergeSpanArr.push(1);
          this.mergeSpanArrIndex = 0
        } else {
        // 判断当前元素与上一个元素是否相同
        if (data[i].indicator === data[i - 1].indicator) {//如何判断出是合并哪一个
            this.mergeSpanArr[this.mergeSpanArrIndex] += 1;
            this.mergeSpanArr.push(0);
          } else {
            this.mergeSpanArr.push(1);
            this.mergeSpanArrIndex = i;
          }
        }
      }
    },

    checkRight(value) {
 
    }

  },
    
  
};
</script>

<style>
.title {
  text-align: center;
  font-weight: bold;
  font-size: 25px;
  padding: 10px 0 15px 0;
}
/* .leftBox{
  position: relative;
  padding-bottom: 10px;
} */
.tableClass {
  width: 60%;
  margin: 0 auto;

  /* display: flex;
    align-items: center;
    justify-content: center; */
}
</style>